//
//  LXFoodViewController.m
//  bgms_d
//
//  Created by Mountain on 2/3/2019.
//  Copyright © 2019 lachesis-zhu. All rights reserved.
//

#import "LXFoodViewController.h"
#import "LXFoodAddViewController.h"
#import "LXHomeViewController.h"
#import "LXFoodRangeVC.h"
#import "LXFoodEditViewController.h"

#import "LXFoodTableViewCell.h"
#import "LXFoodItem.h"
#import "LXSheetView.h"
#import "DataModal.h"
#import "LXPlistManager.h"

@interface LXFoodViewController () <UITableViewDelegate, UITableViewDataSource, LXSheetViewDelegate, LXFoodTableViewCellDelegate, LXActionSheetDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *originArray;
@property (nonatomic, strong) NSMutableArray *levelArray;
@property (nonatomic, strong) NSMutableArray *levelNumArray;
@property (nonatomic, strong) NSMutableArray *levelArray1;
@property (nonatomic, strong) NSMutableArray *levelNumArray1;
@property (nonatomic, strong) NSMutableArray *levelArray2;
@property (nonatomic, strong) NSMutableArray *levelNumArray2;
@property (nonatomic, strong) LXFoodTableViewCell *currentCell;

@end

@implementation LXFoodViewController

#pragma mark -  public method
- (void)removEditItem {
    NSArray *foodList = [[LXPlistManager manager] readFoodDataCache];
    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:foodList];
    [tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *item = obj;
        if ([item[@"name"] isEqualToString:self.editItem.name]) {
            [tempArray removeObject:item];
            self.dataArray.count > idx ? [self.dataArray removeObjectAtIndex:idx] : @"";
            *stop = YES;
        }
    }];
    [[LXPlistManager manager] writeFoodDataCache:tempArray];
    [self.tableView reloadData];
    self.editItem = [LXFoodItem new];
}
#pragma mark -  life cycle
- (void)dealloc
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationData];
    [self addNotification];
    
    [self loadUI];
    
    [self loadViewDatas];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    if (self.addItem && self.addItem.name != nil) {
        __block BOOL sameName;
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodItem *item = obj;
            if ([item.name isEqualToString:self.addItem.name]) {
                sameName = YES;
                *stop = YES;
            }
        }];
        if (sameName) {
            [EasyTextView showErrorText:NSLocalizedString(@"TheNameAlready", nil)];
            self.addItem = [LXFoodItem new];
            return;
        }
        [self.dataArray addObject:self.addItem];
        [self.originArray addObject:self.addItem];
        [self.tableView reloadData];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        NSDictionary *dic = @{@"selected" : @"NO",
                                  @"image" : self.addItem.image,
                                  @"name" : self.addItem.name,
                                  @"cookedLevel" : self.addItem.cookedLevel,
                                  @"setNum" : self.addItem.setNum,
                                  @"minNum" : self.addItem.minNum,
                                  @"unit" : [LXDevSettingModel shareSettingModel].tempUnitF ? @"°F" : @"°C",
                                  @"show" : [NSString stringWithFormat:@"%d", self.addItem.show],
                                  @"rangeTemp" : [NSString stringWithFormat:@"%d", self.addItem.rangeTemp]};
        NSArray *foodList = [[LXPlistManager manager] readFoodDataCache];
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:foodList];
        [tempArray addObject:dic];
        [[LXPlistManager manager] writeFoodDataCache:tempArray];
        self.addItem = [LXFoodItem new];
    }
    
    if (self.editItem && self.editItem.name != nil) {
        NSDictionary *dic = @{@"selected" : @"NO",
                              @"image" : self.editItem.image,
                              @"name" : self.editItem.name,
                              @"cookedLevel" : self.editItem.cookedLevel,
                              @"setNum" : self.editItem.setNum,
                              @"minNum" : self.editItem.minNum,
                              @"unit" : [LXDevSettingModel shareSettingModel].tempUnitF ? @"°F" : @"°C",
                              @"show" : [NSString stringWithFormat:@"%d", self.editItem.show],
                              @"rangeTemp" : [NSString stringWithFormat:@"%d", self.editItem.rangeTemp]};
        NSArray *foodList = [[LXPlistManager manager] readFoodDataCache];
        NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:foodList];
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodItem *item = obj;
            if ([item.name isEqualToString:self.editItem.name]) {
                item.setNum = self.editItem.setNum;
                item.minNum = self.editItem.minNum;
                item.selected = YES;
                [tempArray replaceObjectAtIndex:idx withObject:dic];
                *stop = YES;
            }
        }];
        [self.tableView reloadData];
        [[LXPlistManager manager] writeFoodDataCache:tempArray];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
#pragma mark -  over write

#pragma mark -  setter & getter

#pragma mark -  private method
- (void)initializationData
{
    NSArray *foodList = [[LXPlistManager manager] readFoodDataCache];
    if (!foodList) {
        foodList = [[LXPlistManager manager] getFoodList];
        [[LXPlistManager manager] writeFoodDataCache:foodList];
    }
    
    [foodList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = [LXFoodItem yy_modelWithDictionary:obj];
        item.unit = [LXDevSettingModel shareSettingModel].tempUnitF ? @"°F" : @"°C";
        [self.dataArray addObject:item];
    }];
    self.originArray = [[NSMutableArray alloc] initWithArray:self.dataArray];
    if (self.tempItem && self.tempItem.name != nil) {
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LXFoodItem *item = obj;
            if ([item.name isEqualToString:self.tempItem.name]) {
                item.selected = YES;
                self.editItem = item;
                self.originItem = item;
                *stop = YES;
            }
        }];
    }
}

- (void)loadUI
{
    self.view.backgroundColor = kAppBackgroundColor;
    [self buildNavi];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXFoodTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)loadViewDatas
{
    
}

- (void)buildNavi
{
    [self.navigationView drawAroundViewWithLocation:DrawBottom color:kAppLinesColor insets:UIEdgeInsetsMake(-0.5, 0, 0, 0)];
    if (IPHONE_X) {
        self.naviHeight.constant = 66 + 22;
    }
//    UIButton *editBtn = [[UIButton alloc] init];
//    [editBtn setImage:[UIImage imageNamed:@"编辑"] forState:UIControlStateNormal];
//    [editBtn addTarget:self action:@selector(editDown:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *editBar = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
//    self.navigationItem.rightBarButtonItem = editBar;
}

- (void)devTempSend:(LXFoodItem *)item {
    NSMutableData *sendData = [[NSMutableData alloc] init];
    for (NSInteger i = 0; i < 6; i ++) {
        if (i == self.tempItem.placeNum) {
            NSInteger tempNum = [item.setNum integerValue];
            UInt8 MessageBt[2];
            MessageBt[0] = tempNum & 0xff;
            MessageBt[1] = tempNum & 0x00ff;
            NSData *content = [NSData dataWithBytes:MessageBt length:2];
            [sendData appendData:content];
        } else {
            UInt8 MessageBt[2];
            MessageBt[0] = 0x00;
            MessageBt[1] = 0x00;
            NSData *content = [NSData dataWithBytes:MessageBt length:2];
            [sendData appendData:content];
        }
    }
    Byte *dataByte = (Byte *)[sendData bytes];
    [[BLETransDeviceSingleton sharedInstance] characteristc:SET_CHARACTERISTIC_UUID sendHostCmd:dataByte lenght:12];
    [[BLETransDeviceSingleton sharedInstance] secretKeySendTimeAlert:[[LXDevSettingModel shareSettingModel].alertInterval integerValue] boundsAlert:self.tempItem.placeNum alertOn:YES];
}

#pragma mark -  notification
- (void)addNotification
{
    
}

#pragma mark -  network


#pragma mark -  event handle
- (IBAction)editDown:(UIButton *)sender
{
    if (!self.editItem || [self.editItem.name isEqualToString:@""]) {
        [EasyTextView showInfoText:NSLocalizedString(@"PleaseSelectKinds", nil)];
        return;
    }
    LXFoodEditViewController *vc = [[LXFoodEditViewController alloc] initWithNibName:NSStringFromClass([LXFoodEditViewController class]) bundle:nil];
    vc.editItem = self.editItem;
    vc.originItem = self.originItem;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)backDown:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)removeDown:(UIButton *)sender {
    __block LXFoodItem *backItem;
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = obj;
        if (item.selected) {
            backItem = item;
            *stop = YES;
        }
    }];
    backItem.setNum = @"";
    LXHomeViewController *homeVC =  [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
    homeVC.foodItem = backItem;
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)setDown:(UIButton *)sender {
    __block LXFoodItem *backItem;
    __block NSInteger seletIndex = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = obj;
        if (item.selected) {
            backItem = item;
            seletIndex = idx;
            *stop = YES;
        }
    }];
    if (seletIndex == -1) {
        [EasyTextView showErrorText:NSLocalizedString(@"PleaseSelectKinds", nil)];
        return;
    }
    LXFoodItem *item = [self.dataArray objectAtIndex:seletIndex];
    backItem.setNum = item.setNum;
    backItem.cookedLevel = item.cookedLevel;
    backItem.placeNum = self.tempItem.placeNum;
    LXHomeViewController *homeVC =  [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];
    homeVC.foodItem = backItem;
    [homeVC sendSettingData:backItem];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addDown:(UIButton *)sender
{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXSheetView class]) owner:nil options:nil];
    LXSheetView *sheetView = [array firstObject];
    [UIView animateWithDuration:1 animations:^{
        sheetView.frame = self.view.window.bounds;
    }];
    sheetView.delegate = self;
    [self.view.window addSubview:sheetView];
    
}
#pragma mark -  delegate
#pragma mark
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, [LXAutoLength lx_L:64])];
    footView.backgroundColor = kAppBackgroundColor;
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenWidth - [LXAutoLength lx_L:30]) / 2, [LXAutoLength lx_L:17], [LXAutoLength lx_L:30], [LXAutoLength lx_L:30])];
    [addBtn setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addDown:) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:addBtn];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return [LXAutoLength lx_L:64];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [LXAutoLength lx_L:52];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LXFoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.delegate = self;
    [cell drawAroundViewWithLocation:DrawBottom color:kAppLinesColor insets:UIEdgeInsetsMake(0, 0, 0.5, 0)];
    LXFoodItem *item = [self.dataArray objectAtIndex:indexPath.row];
    cell.selectBtn.selected = item.selected;
    cell.typeImage.image = [UIImage imageNamed:item.image];
    cell.nameLabel.text = NSLocalizedString(item.name, nil);
    NSString *detailString = @"";
    if (item.rangeTemp) {
        detailString = [NSString stringWithFormat:@"%@~%@", [[LXDevSettingModel shareSettingModel] tempCTempF:item.minNum], [[LXDevSettingModel shareSettingModel] tempCTempF:item.setNum]];
    } else {
        if (indexPath.row == 0) {
            detailString = [NSString stringWithFormat:@"%@ %@", [self.levelArray firstObject], [[LXDevSettingModel shareSettingModel] tempCTempF:[self.levelNumArray firstObject]]];
        } else if (indexPath.row == 1) {
            detailString = [NSString stringWithFormat:@"%@ %@", [self.levelArray1 firstObject], [[LXDevSettingModel shareSettingModel] tempCTempF:[self.levelNumArray1 firstObject]]];
        } else if (indexPath.row == 2) {
            detailString = [NSString stringWithFormat:@"%@ %@", [self.levelArray2 firstObject], [[LXDevSettingModel shareSettingModel] tempCTempF:[self.levelNumArray2 firstObject]]];
        } else {
            detailString = [NSString stringWithFormat:@"%@ %@", [self.levelArray objectAtIndex:[item.cookedLevel integerValue]], [[LXDevSettingModel shareSettingModel] tempCTempF:item.setNum]];
        }
    }
    cell.detailLabel.text = detailString;
    cell.viewWidth.constant = item.show ? 8 : 0;
    if (indexPath.row > 4) {
        cell.viewWidth.constant = 0;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = obj;
        if (indexPath.row == idx) {
            item.selected = YES;
        } else {
            item.selected = NO;
        }
        LXFoodTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
        cell.selectBtn.selected = NO;
    }];
    LXFoodTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.selectBtn.selected = YES;
    self.editItem = [self.dataArray objectAtIndex:indexPath.row];
    self.originItem = [self.originArray objectAtIndex:indexPath.row];
}

#pragma mark - LXSheetViewDelegate
- (void)sheetView:(LXSheetView *)sheetView selectIndex:(NSInteger)index
{
    [sheetView removeFromSuperview];
    if (index == 1) {
        LXFoodAddViewController *vc = [[LXFoodAddViewController alloc] initWithNibName:NSStringFromClass([LXFoodAddViewController class]) bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        LXFoodRangeVC *vc = [[LXFoodRangeVC alloc] initWithNibName:NSStringFromClass([LXFoodRangeVC class]) bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - LXActionSheetDelegate
- (void)LXActionSheet:(LXActionSheet *)actionSheet didSelectIndex:(NSInteger)buttonIndex
{
    NSArray *tempLevelArray;
    NSArray *tempLevelNumArray;
    if (actionSheet.tag == 0) {
        tempLevelArray = [NSArray arrayWithArray:self.levelArray];
        tempLevelNumArray = [NSArray arrayWithArray:self.levelNumArray];
    } else if (actionSheet.tag == 1) {
        tempLevelArray = [NSArray arrayWithArray:self.levelArray1];
        tempLevelNumArray = [NSArray arrayWithArray:self.levelNumArray1];
    } else if (actionSheet.tag == 2) {
        tempLevelArray = [NSArray arrayWithArray:self.levelArray2];
        tempLevelNumArray = [NSArray arrayWithArray:self.levelNumArray2];
    }
    NSString *selectType = [tempLevelArray objectAtIndex:buttonIndex];
    NSString *selectNum = [tempLevelNumArray objectAtIndex:buttonIndex];
    self.currentCell.detailLabel.text = [NSString stringWithFormat:@"%@ %@", selectType, [[LXDevSettingModel shareSettingModel] tempCTempF:selectNum]];;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:self.currentCell];
    LXFoodItem *item = [self.dataArray objectAtIndex:indexPath.row];
    item.cookedLevel = [NSNumber numberWithInteger:buttonIndex];
    item.setNum = selectNum;
    [self.dataArray replaceObjectAtIndex:indexPath.row withObject:item];
}
#pragma mark - LXFoodTableViewCellDelegate
- (void)foodTableViewCellSelect:(LXFoodTableViewCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        LXFoodItem *item = obj;
        if (indexPath.row == idx) {
            item.selected = YES;
        } else {
            item.selected = NO;
        }
        LXFoodTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:idx inSection:0]];
        cell.selectBtn.selected = NO;
    }];
    cell.selectBtn.selected = YES;
    self.editItem = [self.dataArray objectAtIndex:indexPath.row];
    self.originItem = [self.originArray objectAtIndex:indexPath.row];
}

- (void)foodCellTypeSelect:(LXFoodTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row > 2) {
        return;
    }
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    if (indexPath.row == 0) {
        [self.levelArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *temp1 = obj;
            NSString *temp2 = [self.levelNumArray objectAtIndex:idx];
            NSString *tempAdd = [NSString stringWithFormat:@"%@~%@", temp1, [[LXDevSettingModel shareSettingModel] tempCTempF:temp2]];
            [newArray addObject:tempAdd];
        }];
    } else if (indexPath.row == 1) {
        [self.levelArray1 enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *temp1 = obj;
            NSString *temp2 = [self.levelNumArray1 objectAtIndex:idx];
            NSString *tempAdd = [NSString stringWithFormat:@"%@~%@", temp1, [[LXDevSettingModel shareSettingModel] tempCTempF:temp2]];
            [newArray addObject:tempAdd];
        }];
    } else if (indexPath.row == 2) {
        [self.levelArray2 enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *temp1 = obj;
            NSString *temp2 = [self.levelNumArray2 objectAtIndex:idx];
            NSString *tempAdd = [NSString stringWithFormat:@"%@~%@", temp1, [[LXDevSettingModel shareSettingModel] tempCTempF:temp2]];
            [newArray addObject:tempAdd];
        }];
    }
    
    LXActionSheet *sheet = [[LXActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) destructiveButtonTitle:@"" otherButtonTitles:newArray];
    [sheet showInView:self.view];
    sheet.tag = indexPath.row;
    self.currentCell = cell;
}

#pragma mark -  lazy load
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSMutableArray *)levelArray {
    if (!_levelArray) {
        _levelArray = [[NSMutableArray alloc] initWithObjects:NSLocalizedString(@"Rare", nil), NSLocalizedString(@"M.Rare", nil), NSLocalizedString(@"Medium", nil), NSLocalizedString(@"M.Well", nil), NSLocalizedString(@"Well", nil),  nil];
    }
    return _levelArray;
}

- (NSMutableArray *)levelNumArray {
    if (!_levelNumArray) {
        _levelNumArray = [[NSMutableArray alloc] initWithObjects:@"60", @"62", @"71", @"73", @"76", nil];
    }
    return _levelNumArray;
}

- (NSMutableArray *)levelArray1 {
    if (!_levelArray1) {
        _levelArray1 = [[NSMutableArray alloc] initWithObjects:NSLocalizedString(@"M.Rare", nil), NSLocalizedString(@"Medium", nil), NSLocalizedString(@"M.Well", nil), NSLocalizedString(@"Well", nil),  nil];
    }
    return _levelArray1;
}

- (NSMutableArray *)levelNumArray1 {
    if (!_levelNumArray1) {
        _levelNumArray1 = [[NSMutableArray alloc] initWithObjects:@"60", @"62", @"71", @"76", nil];
    }
    return _levelNumArray1;
}

- (NSMutableArray *)levelArray2 {
    if (!_levelArray2) {
        _levelArray2 = [[NSMutableArray alloc] initWithObjects:NSLocalizedString(@"M.Rare", nil), NSLocalizedString(@"Medium", nil), NSLocalizedString(@"M.Well", nil), NSLocalizedString(@"Well", nil),  nil];
    }
    return _levelArray2;
}

- (NSMutableArray *)levelNumArray2 {
    if (!_levelNumArray2) {
        _levelNumArray2 = [[NSMutableArray alloc] initWithObjects:@"62", @"71", @"73", @"76",  nil];
    }
    return _levelNumArray2;
}
#pragma mark -  memoryWarning

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
